package org.lex.utils.text;

/**
 * ֻʹ��һ���ַ���Ϊ"�ָ���"������"�ָ���"������Ϊ��token��<br>
 * ���ַ�Ҳ����Ϊ��token
 * 
 * @author Daniel Liu
 */
public class SingleCharDelimiterTokenizer implements Tokenizer {
	public static void main(String[] args) {
		SingleCharDelimiterTokenizer mt = null;
		mt = new SingleCharDelimiterTokenizer(null, '.', false);
		String[] samples = { "a.b.c", "...a", "...", "a...", "a...b..", "abc", "" };
		for (String s : samples) {
			mt.reset(s);
			System.out.print(s + "\t: ");
			while (mt.hasNext())
				System.out.print("[" + mt.next() + "]  ");
			System.out.println();
		}
	}

	private String src = null;
	private char sep = ' ';
	private boolean allowEmptyToken = true;
	// --------------------
	private int from = 0;
	private int to = -1;

	public SingleCharDelimiterTokenizer(String source, char sep, boolean allowEmptyToken) {
		this.reset(source, sep);
		this.allowEmptyToken = allowEmptyToken;
	}

	public void reset() {
		this.reset(this.src, this.sep);
	}

	public void reset(char sep) {
		this.reset(this.src, sep);
	}

	public void reset(String source) {
		this.reset(source, this.sep);
	}

	public void reset(String source, char sep) {
		this.src = source;
		this.sep = sep;
		this.from = 0;
		this.to = -1;
		this.nextTokenHasCalculated = false;
	}

	public String[] split(String source) {
		this.reset(source);
		return null;
	}

	public int getLeftTokenCount() {
		int count = 0;
		while (hasNext()) {
			next();
			count++;
		}
		return count;
	}

	private boolean hasNext = false;
	private boolean nextTokenHasCalculated = false;

	public boolean hasNext() {
		if (false == nextTokenHasCalculated) {
			if (to == src.length()) {
				// reach end
				hasNext = false;
			} else {
				from = to + 1;
				to = src.indexOf(sep, from);
				if (-1 == to)
					to = src.length();
				if (false == this.allowEmptyToken && from == to)
					return hasNext();
				hasNext = true;
			}
			nextTokenHasCalculated = true;
		}
		return hasNext;
	}

	public String next() {
		nextTokenHasCalculated = false;
		return src.substring(from, to);
	}

	public void remove() {
	}
}
